"""
@author: yinjx
@file: addcomment.py
@time: 2023/8/11 16:11
"""

from . import addcomment_bp

from . import addcomment_bp

from models.user import Book
from flask import Blueprint, jsonify, request
from flask_restful import Api, Resource
from models.user import User, Book, Category, Comment
from models import db
import datetime
import json
from libs.response import generate_response
from functools import wraps
import time
from datetime import datetime
from flask import request, current_app
from models.user import ApiToken
from hashlib import md5
import jwt
from jwt.exceptions import ExpiredSignatureError, InvalidSignatureError
from libs.error_code import AuthorizedFailException, TokenFailException

api = Api(addcomment_bp)


def token_reauth(func):

        def decorated(*args, **kwargs):
            # print("获取到token")
            token = request.headers.get("token")
            print(token)
            if token:
                try:
                    print(time.time())
                    jwt_obj = jwt.decode(token, current_app.config.get("SECRET_KEY"),
                                         algorithms=["HS256"])
                except InvalidSignatureError as e:
                    print("token不合法", e)
                    raise TokenFailException
                except ExpiredSignatureError as e:
                    print("token过期", e)
                    raise TokenFailException
                print("验证token")
                return func(*args, **kwargs)
            else:
                return False

        return decorated





class AddComment(Resource):
    @token_reauth
    def post(self, book_id):
        book = Book.query.get(book_id)        # 获取当前登录用户的ID

        my_user = request.json.get('my_user')
        book_id = request.json.get('bookId')
        content = request.json.get('content')
        print(book_id)
        user = User.query.filter_by(username=my_user).first()
        book = Book.query.filter_by(id=book_id).first()
        print("得到了book  content")
        user_id = user.id
        book_id = book.id

        # 构建评论对象
        comment = Comment(content=content, created_at=datetime.now(), user_id=user_id, book_id=book_id)
        # comment = Comment(content=content, created_at=datetime.datetime.now(), user_id=user_id, book_id=book_id)
        print("添加到了数据库")
        # 将评论存储到数据库
        db.session.add(comment)
        db.session.commit()

        response = generate_response(code=200, message='评论添加成功')
        return jsonify(response)


api.add_resource(AddComment, "/book/<int:book_id>/comments", endpoint="book_comments")